import { Button, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';

import $utils from '@/utils/utils';
import { getExpressData, searchExpressList, } from '@/services/company';

const userInfo = $utils.getStorage('user_info');

const BasicConfig: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const actionRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const access = useAccess();

    const [initParams, setParams] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);
    const [expressList, setExpressList] = useState<API.Select[]>([]);

    // 快递公司列表
    useEffect(() => {
        const getOptions = async () => {
            let result = await getExpressData();

            setExpressList(result);
        };
        getOptions();
    }, []);


    const l_state: any = history.location.state;
    useEffect(() => {
        if (!initParams) {
            const data = {
                ...l_state,
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        if (JSON.stringify(initParams) === '{}') {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    const columns: ProColumns<any>[] = [
        {
            title: 'ID',
            dataIndex: 'id',
            search: false,
        },
        {
            title: '快递公司',
            dataIndex: 'name',
            valueType: 'select',
            fieldProps: {
                options: expressList,
                showSearch: true,
                placeholder: '全部快递公司'
            },
        },
        {
            title: '添加人',
            dataIndex: 'createUserName',
            // sorter: true,
            search: false,
            hideInForm: true,
        },
        {
            title: '添加时间',
            dataIndex: 'createTime',
            search: false,
            hideInForm: true,
            width: '120px',
        },
        {
            title: '最新修改人',
            dataIndex: 'updateUserName',
            search: false,
            hideInForm: true,
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            search: false,
            hideInForm: true,
            width: '120px',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Access key={record.id} accessible={access.can_companyAll.update} >
                    <Button key={record.id} type="primary" size="small" onClick={() => {

                        const newTab = {
                            name: `编辑${record.name}`,
                            path: '/BasicConfig/Company/detail',
                            state: {
                                status: 'update',
                                data: record
                            }
                        };
                        // 设置当前tab对象
                        $utils.setNewTab(dispatch, newTab);
                        $utils.addTab(dispatch, newTab)

                        history.push({
                            pathname: '/BasicConfig/Company/detail',
                            state: {
                                status: 'update',
                                data: record
                            }
                        });
                    }}>编辑</Button>
                </Access>

            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                options={false}
                form={{
                    initialValues: initParams
                }}
                formRef={formRef}
                search={access.can_companyAll.search ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: {
                        xs: 24,
                        sm: 24,
                        md: 12,
                        lg: 12,
                        xl: 8,
                        xxl: 8,
                    },
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                setParams({});
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                title={() => [
                    <Access key="index" accessible={access.can_companyAll.create}>
                        <Button type="primary" onClick={() => {
                            const newTab = {
                                name: `新建快递公司`,
                                path: '/BasicConfig/Company/detail',
                                state: {
                                    status: 'create',
                                    data: expressList
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)

                            history.push({
                                pathname: '/BasicConfig/Company/detail',
                                state: {
                                    status: 'create',
                                    data: expressList
                                }
                            });
                        }}>新建快递公司</Button>
                    </Access>
                ]}
                params={{
                    sessionId: userInfo.sessionId
                }}
                request={async (params) => {
                    params.name && (params.id = params.name);
                    const msg = await searchExpressList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '快递公司',
                            path: '/BasicConfig/company',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.data || [],
                        success: msg.code === 0,
                        total: msg.body?.total,
                    }
                }}
                columns={columns}
            />}
        </PageContainer >
    );
};

export default BasicConfig;
